// pages/classify/index.js
import images from '../../utils/images.js'
const app = getApp()
Page({
  data: {
    ...app.globalData.config,
    tabList: [
    ],
    current: '1',
    offset: '0rpx',
    offsetTimeout: null,
    list: [],
    empty_hidden: true,
    tip_hidden: false,

    mutil_rule_hidden: true
  },
  getOffset(){
      const offsetTimeout = setTimeout(() => {
        let query = wx.createSelectorQuery();
        query.select('.header').boundingClientRect(rect=>{
          try{
            let clientHeight = rect.height;
            let clientWidth = rect.width;
            let ratio = 750 / clientWidth;
            let height = clientHeight * ratio;
            this.setData({
              offset: `${height||0}rpx`
            })
          }catch(e){
            console.log("ERROR:获取分类页头部高度失败")
          }
        }).exec();
      }, 300)
      this.setData({offsetTimeout})
    
  },

  openCloseMutilRule() {
    var hidden = this.data.mutil_rule_hidden;
    if (hidden) {
      hidden = false;
    } else {
      hidden = true;
    }

    this.setData({
      mutil_rule_hidden: hidden
    });
  },
  
  clickTabChild(e) {
    var that = this,
        id = e.currentTarget.dataset.id,
        newTabList = [];

    that.data.tabList.forEach(it => {
      if (id == it.dictId) {
        if (typeof it.selected != 'undefined' && it.selected) {
          it.selected = false;
        } else {
          it.selected = true;
        }
      }
      newTabList.push(it);
    });

    that.setData({
      tabList: newTabList
    });
  },

  filterClears() {
    var that = this,
        newTabList = [];
    that.data.tabList.forEach(it => {
      it.selected = false;
      newTabList.push(it);
    });

    that.setData({
      tabList: newTabList
    });
  },

  filterSubmit() {
    var that = this,
        selectedIdList = [];
    that.data.tabList.forEach(it => {
      if (typeof it.selected != 'undefined' && it.selected) {
        selectedIdList.push(it.dictId);
      }
    });
    that.setData({
      mutil_rule_hidden: true
    });

    that.searchProduct(
      {
        ruleIdList: selectedIdList
      }
    )
  },

  getRuleList(){
    var that = this;
    wx.request({
      url: app.globalData.context + '/setting/dict/list/constant/product_rule',
      success: function(result) {
        that.setData({
          tabList: result.data.data
        });
      }
    })
  },

  getSubRuleList(parentId) {
    var that = this;
    wx.request({
      url: app.globalData.context + '/setting/dict/list/parent-id/' + parentId,
      success: function(res) {
        var result = res.data;
        if (result.success) {
          if (result.data == null || result.data.length <= 0) {
            that.searchProduct({ruleIdList:[parentId]});
          } else {
            var itemList = [];
            result.data.forEach(it => {
              itemList.push(it.dictName);
            });
  
            wx.showActionSheet({
              itemList: itemList,
              success (res) {
                that.searchProduct({ruleIdList:[result.data[res.tapIndex].dictId]});
              },
              fail (res) {
                console.log(res.errMsg)
              }
            });
          }
        }       
      }
    })
  },

  searchProduct(condition) {
    var that = this;

    wx.request({
      method:'post',
      url: app.globalData.context + '/bu/product/search',
      data: condition,
      success: function(res) {
        console.log(res)
        // 清空原来的数据
        that.setData({
          tip_hidden: true,
          list:[]
        });

        var result = res.data;
        if (result.success) {
          if (result.data == null || result.data.length <= 0) {
            that.setData({
              empty_hidden: false,
              list:[]
            });
          } else {
            var productList = [];
            result.data.forEach(it => {
              it.url = app.globalData.context + '/setting/file/output?fileUrl=' + it.productLogo;
              productList.push(it);
            });
            that.setData({
              empty_hidden: true,
              list:productList
            });
          }
        }
      }
    })
  },

  handleChange({ detail }){
    this.setData({
      current: detail.key
    })
    this.getSubRuleList(detail.key);
  },

  toProdunctDetail(ev) {
    let info = ev.currentTarget.dataset;
    let navigateUrl = '../../pagesProduct/index?';
    for (let key in info) {
        info[key] = encodeURIComponent(info[key]);
        navigateUrl += key + '=' + info[key] + '&';
    }
    navigateUrl = navigateUrl.substring(0, navigateUrl.length - 1);
    wx.navigateTo({
        url: navigateUrl
    });
  },

  onLoad(){
    setTimeout(()=>{
      this.selectComponent("#page").hideLoading()
      this.getOffset() // 计算头部高度
    },2000);

    this.getRuleList();
  },
  onShow(){
    this.getOffset() // 计算头部高度
  },
  onUnload(){
    if(this.data.offsetTimeout) clearTimeout(this.data.offsetTimeout)
  },
  onShareAppMessage() {
    return {
      title: '企运融'
    }
  },
  onShareTimeline() {}
})